<script>
import QSGDrawer from "@/components/QSGDrawer/index.vue";
import {uploadSound} from "@/api/aihuman/humanAssets/soundType";
import {addOrUpdateFont} from "@/api/aihuman/humanAssets/font";
import {uploadFile} from "@/api/aihuman/common/minio";
import {getUrl} from "@/util/aihuman/getUrl";

export default {
  name: "AddFont",
  components: {QSGDrawer},
  data() {
    //检验声音id
    var checkType = (rule, value, callback) => {
      // var inputType = /[^\w]/g
      var inputReg = /[a-zA-Z0-9-_]/g;
      if (!inputReg.test(value)) {
        callback(new Error('id由数字、英文、短划线、下划线组成'))
      } else {
        callback()
      }
    };
    return {
      typesList: [
        {
          label: '背景',
          value: 2
        },
        {
          label: '图片',
          value: 1
        }
      ],
      formStatus: 'add',
      showDrawer: false,
      title: "新增",
      loading: false,
      groupId: '',
      form: {
        name: '',
        enable: true,
        filePath: '',
        filePathObj: '',
        styleCode: ''
      },
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入字体名称',
            trigger: 'blur'
          },
          {min: 1, max: 30, message: '长度不可超过30个字符', trigger: 'blur'}
        ],
        styleCode: [
          {
            required: true,
            message: '请输入字体code',
            trigger: 'blur'
          },
          {min: 1, max: 30, message: '长度不可超过30个字符', trigger: 'blur'}
        ],
        filePathObj: [
          {required: true, message: '请上传字体文件', trigger: 'change'},
        ]
      }
    }
  },
  methods: {
    getUrl,
    open(type, data = {}) {
      if (type === 'add') {
        this.showDrawer = true
        this.formStatus = type
        this.title = '新增'

        this.form = {
          name: '',
          enable: true,
          filePath: '',
          filePathObj: '',
          styleCode: ''
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
          this.$refs.uploadFont.clearFiles()
        })
      } else if (type === 'preview') {
        this.title = '查看'
        this.formStatus = type
        this.showDrawer = true
        // this.form = {...data}
        this.form.id = data.id
        this.form.enable = data.enable
        this.form.name = data.name
        this.form.styleCode = JSON.parse(data.filePath).originalFileName
        this.form.filePathObj = JSON.parse(data.filePath)

        // 使用 FontFace API 加载字体
        const font = new FontFace(this.form.filePathObj.originalFileName,
          `url(${this.getUrl()}${this.form.filePathObj.url})`);

        font.load().then(function(loadedFont) {
          // 将字体添加到 document 中
          document.fonts.add(loadedFont);

          // 应用字体
          // document.querySelector('.font-preview').style.fontFamily = this.form.filePathObj.originalFileName;
        }).catch(function(error) {
          console.error('字体加载失败:', error);
        });

      } else {
        this.title = '编辑'
        this.formStatus = type
        this.showDrawer = true
        this.form.id = data.id
        this.form.enable = data.enable
        this.form.name = data.name
        this.form.styleCode = JSON.parse(data.filePath).originalFileName
        this.form.filePathObj = JSON.parse(data.filePath)

        // 使用 FontFace API 加载字体
        const font = new FontFace(this.form.filePathObj.originalFileName,
          `url(${window.location.origin}${this.form.filePathObj.url})`);

        font.load().then(function(loadedFont) {
          // 将字体添加到 document 中
          document.fonts.add(loadedFont);

          // 应用字体
          // document.querySelector('.font-preview').style.fontFamily = this.form.filePathObj.originalFileName;
        }).catch(function(error) {
          console.error('字体加载失败:', error);
        });

      }
    },
    removeFile(file, fileList) {
      console.log(file, fileList)
      this.form.styleCode = ''
      this.form.filePathObj = ''
    },
    async uploadFont(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      formData.append('keyFolderPath', 'HumanAssets/font')

      const {data} = await uploadFile(formData)
      // this.form.filePath = JSON.stringify(data.data)
      this.form.filePathObj = {
        originalFileName: data.data.oldFileName.split('.')[0],
        bucketName: data.data.bucketName,
        url: data.data.filePath,
        fileName: data.data.oldFileName,
        realBucketName: null
      }

      this.form.styleCode = data.data.oldFileName.split('.')[0]
      this.$refs.form.validateField('filePathObj')
    },
    closeDawer() {
      this.showDrawer = false
    },
    changeStyleCode(val) {
      console.log(val);
      // this.form.filePathObj.originalFileName = val

    },
    downFont(file) {
      console.log(file);
      const a = document.createElement('a');
      a.href = `${window.location.origin}/` + file.url;
      a.download = file.originalFileName || 'download';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    copyLink(file) {
      navigator.clipboard.writeText(`${window.location.origin}/` + file.url).then(() => {
        this.$message.success('复制成功')
      }).catch(err => {
        console.error('Failed to copy text: ', err);
      });
    },
    submitData() {
      this.loading = true
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.form.filePathObj.originalFileName =  this.form.styleCode
          let params = {
            id: this.form.id || '',
            name: this.form.name,
            enable: this.form.enable,
            filePath: JSON.stringify(this.form.filePathObj)
          }

          try {
            const {data} = await addOrUpdateFont(params)
            console.log(data);
            this.loading = false
            this.$message.success(data.msg)
            this.showDrawer = false
            this.$emit('save')
          } catch (e) {
            console.log(e);
            this.loading = false
          }

        } else {
          console.log('error submit!!');
          this.loading = false
          return false;
        }
      });
    }
  }
}
</script>

<template>
  <q-s-g-drawer
    ref="drawer"
    :visible.sync="showDrawer"
    size="600px"
    :title="title"
  >

    <el-form ref="form" :model="form" :rules="rules" label-width="90px" size="small">
      <el-form-item label="字体名称:" prop="name">
        <el-input v-if="formStatus !== 'preview'" v-model="form.name"></el-input>
        <div v-else>{{ form.name }}</div>
      </el-form-item>

      <el-form-item v-if="form.filePathObj" label="样式code:" prop="styleCode">
        <el-input v-if="formStatus !== 'preview'" v-model="form.styleCode"
                  @input="changeStyleCode"
        ></el-input>
        <div v-else>{{ form.styleCode }}</div>
      </el-form-item>

      <el-form-item label="启用状态:">
        <el-switch
          v-model="form.enable"
          active-text="停用"
          inactive-text="启用"
          :active-value="true"
          :disabled="formStatus === 'preview'"
          :inactive-value="false"
        >
        </el-switch>
      </el-form-item>

      <el-form-item v-if="formStatus !== 'edit'" label="字体文件:" prop="filePathObj">
        <el-upload
          v-if="formStatus === 'add'"
          ref="uploadFont"
          class="upload-demo"
          :http-request="uploadFont"
          accept=".ttf"
          limit="1"
          :show-file-list="true"
          :on-remove="removeFile"
          drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传格式为 .ttf, .TTF 的文件
          </div>
        </el-upload>

        <div v-if="formStatus === 'preview' && form.filePathObj || formStatus === 'preview'">
          <el-button type="text" @click="downFont(form.filePathObj)">下载文件</el-button>
          <el-button type="text" @click="copyLink(form.filePathObj)">复制链接</el-button>
        </div>
      </el-form-item>

      <el-form-item v-if="formStatus !== 'add'" label="字体预览">
        <div class="font-preview" :style="{fontFamily: form.filePathObj.originalFileName}">示例字体</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        v-if="formStatus !== 'preview'"
        type="primary"
        icon="el-icon-circle-plus-outline"
        size="small"
        :loading="loading"
        @click="submitData"
      >保 存
      </el-button>
      <el-button
        type="default"
        icon="el-icon-circle-close"
        size="small"
        :loading="loading"
        @click="closeDawer"
      >{{ formStatus === 'preview' ? '关 闭' : '取 消' }}
      </el-button>
    </template>
  </q-s-g-drawer>
</template>

<style scoped lang="scss">
.font-preview {
  font-size: 32px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
